package com.songqi.common.core.utils.sign;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author madison
 * {@code @description}
 * {@code @date} 2023/2/18 21:15
 */
public class ShaUtil {

    public static String getSha1HexString(String source) throws NoSuchAlgorithmException{
        return getShaHexString(source, "SHA-1");
    }

    public static String getSha256HexString(String source) throws NoSuchAlgorithmException {
        return getShaHexString(source, "SHA-256");
    }



    private static String getShaHexString(String source, String algorithm) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        digest.update(source.getBytes(StandardCharsets.UTF_8));
        return toHexString(digest.digest());
    }

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        byte[] var2 = bytes;
        int var3 = bytes.length;

        for (int var4 = 0; var4 < var3; ++var4) {
            byte b = var2[var4];
            sb.append(String.format("%02x", b));
        }

        return sb.toString();
    }
}
